package org.xhy.retryer.strategy;

import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @gitee: https://gitee.com/XhyQAQ
 * @copyright: B站: https://space.bilibili.com/152686439
 * @Author: Xhy
 * @CreateTime: 2024-04-29 21:42
 */
public class ExponentialRetryerStrategy extends RetryerStrategy{

    private  int baseCount = 1;
    public ExponentialRetryerStrategy(int count, long time, TimeUnit timeUnit){
       super(count,time,timeUnit);
    }

    @Override
    public void reset() {
        baseCount = 1;
    }


    @Override
    boolean exec() {
        while (count >= baseCount) {
            try {
                long waitTime = (long) (time * Math.pow(2, baseCount++ - 1));
                timeUnit.sleep(waitTime);
                return true;
            } catch (InterruptedException e) {
                // 在等待期间被中断，抛出异常
                Thread.currentThread().interrupt();
                throw new RuntimeException("Retry interrupted", e);
            }
        }
        // 重试次数达到上限，返回false
        return false;
    }
}
